package minishell.cmdlet.buildin;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import minishell.cmdlet.AbstractCmdlet;
import minishell.object.FileObject;
import minishell.object.IObject;
import minishell.object.format.FileFormatter;
import minishell.object.format.ObjectFormatter;

public class ListCmdlet extends AbstractCmdlet
{
	private static final String NAME = "ls";
	private static final String DESCRIPTION = "list directory contents";
	private static final String USAGE = "ls [OPTION]... [FILE]...";
	
	private ObjectFormatter formatter = null;
	
	public String getName()
	{
		return NAME;
	}

	public String getDescription()
	{
		return DESCRIPTION;
	}

	public String getUsage()
	{
		return USAGE;
	}

	public boolean hasFormatter()
	{
		return true;
	}

	public ObjectFormatter getFormatter()
	{
		if( null == this.formatter )
		{
			formatter = FileFormatter.newFormatter( FileFormatter.Format.LONG );
		}
		return formatter;
	}

	public List<IObject> excute( String command )
	{
		return this.list( this.getEnvironment().getDirectory() );
	}
	
	private List<IObject> list( File dir )
	{
		File[] files = dir.listFiles();
		List<IObject> list = new ArrayList<IObject>( files.length );
		for( File file : files )
			list.add( new FileObject( file ) );
		return list;
	}
}
